import React, { Component } from 'react';
import {
    NavBar,
    InputItem,
    WhiteSpace,
    TextareaItem,
    Button,
    Toast,
} from 'antd-mobile';
import request from '../plugin/request';

class BlogAdd extends Component {
    constructor(props) {
        super(props);

        this.state = {
            title: '',
            content: '',
        };

        this.titleChange = this.titleChange.bind(this);
        this.contentChange = this.contentChange.bind(this);
        this.addBlog = this.addBlog.bind(this);
    }

    titleChange(title) {
        this.setState({ title });
    }

    contentChange(content) {
        this.setState({ content });
    }

    async addBlog() {
        const res = await request.post('/blogs', {
            title: this.state.title,
            content: this.state.content,
        });
        if (res.code !== 201) {
            Toast.fail(res.message);
            return;
        }
        // 跳转到列表页面
        this.props.history.push('/blogs');
    }

    render() {
        return (
            <div className="blog-add">
                {/* 顶部导航 */}
                <NavBar>网站博客</NavBar>

                <WhiteSpace />

                {/* 博客标题输入框 */}
                <InputItem
                    placeholder="请填写标题"
                    onChange={this.titleChange}
                    value={this.state.title}
                >
                    博客标题
                </InputItem>

                <WhiteSpace />

                <TextareaItem
                    rows={5}
                    count={100}
                    title="博客内容"
                    value={this.state.content}
                    placeholder="请填写博客内容"
                    onChange={this.contentChange}
                />

                <WhiteSpace />

                <Button type="primary" onClick={this.addBlog}>
                    发表博客
                </Button>
            </div>
        );
    }
}

export default BlogAdd;
